package net.tensor.skynet.utils

import java.io.*

class StringToInputStreamTest {

    fun test() {
        val str = "学习Java编程"
        println("原字符串：$str")
        // 字符串转输入流
        val inputStream: InputStream = strToInputStream(str)
        println("字符串转化后的流：$inputStream")
        // 输入流转字符串
        val string = inputStreamToString(inputStream)
        println("流还原为字符串：$string")
    }

    /**
     *
     * @Description 字符串转输入流
     * @author fanj
     * @date 2019年11月2日
     * @param str
     * @return
     */
    fun strToInputStream(str: String): InputStream {
        val bytes = str.toByteArray()
        return ByteArrayInputStream(bytes)
    }

    /**
     *
     * @Description 输入流转字符串
     * @author fanj
     * @date 2019年11月2日
     * @param inputStream
     * @return
     */
    fun inputStreamToString(inputStream: InputStream): String? {
        val bufferedReader = BufferedReader(InputStreamReader(inputStream))
        val stringBuffer = StringBuffer()
        var oneLine: String? = ""
        try {
            while (bufferedReader.readLine().also({ oneLine = it }) != null) {
                stringBuffer.append(oneLine)
            }
            return stringBuffer.toString()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

}